#include <stdio.h>

// 有序数组线性查找函数（可提前终止）
int ordered_linear_search(int arr[], int size, int target)
{
    for (int i = 0; i < size; i++)
    { // 遍历数组
        if (arr[i] == target)
        {             // 找到目标元素
            return i; // 返回索引位置
        }
        else if (arr[i] > target)
        {          // 遇到比目标大的元素（因为数组有序）
            break; // 可提前终止查找
        }
    }
    return -1; // 未找到返回-1
}

int main()
{
    // 有序测试数组（升序排列）
    int data[] = {7, 12, 23, 45, 56};
    int size = sizeof(data) / sizeof(data[0]);

    // 情况1：查找成功
    int target1 = 23;
    int result1 = ordered_linear_search(data, size, target1);

    if (result1 != -1)
    {
        printf("Element %d found at index %d.\n", target1, result1); // 输出查找成功信息
    }
    else
    {
        printf("Element %d not found in the array.\n", target1);
    }

    // 情况2：查找失败（目标值存在但不在数组中）
    int target2 = 24;
    int result2 = ordered_linear_search(data, size, target2);

    if (result2 != -1)
    {
        printf("Element %d found at index %d.\n", target2, result2);
    }
    else
    {
        printf("Element %d not found in the array.\n", target2); // 输出查找失败信息
    }

    // 情况3：查找失败（目标值小于最小值）
    int target3 = 5;
    int result3 = ordered_linear_search(data, size, target3);

    if (result3 != -1)
    {
        printf("Element %d found at index %d.\n", target3, result3);
    }
    else
    {
        printf("Element %d not found in the array.\n", target3); // 输出查找失败信息
    }

    // 情况4：查找失败（目标值大于最大值）
    int target4 = 60;
    int result4 = ordered_linear_search(data, size, target4);

    if (result4 != -1)
    {
        printf("Element %d found at index %d.\n", target4, result4);
    }
    else
    {
        printf("Element %d not found in the array.\n", target4); // 输出查找失败信息
    }

    return 0;
}